﻿namespace Example
{
    using System;
    using System.Text;

    public sealed class Dollar
    {
        private readonly string[] _ones = { "zero", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten", "eleven", "twelve", "thirteen", "fourteen", "fifteen", "sixteen", "seventeen", "eighteen", "nineteen" };

        private readonly string[] _tens = { string.Empty, string.Empty, "twenty", "thirty", "forty", "fifty", "sixty", "seventy", "eighty", "ninety" };

        public Dollar(decimal value)
            : this(Convert.ToInt32(Math.Round(value, 0)))
        {
        }

        public Dollar(int value)
        {
            Value = value;
        }

        public int Value { get; set; }

        public override string ToString()
        {
            var buffer = new StringBuilder();

            var thousands = Value / 1000;
            if (0 != thousands)
            {
                buffer.Append(ToString(thousands));
                buffer.Append(" thousand ");
            }

            var remainder = Value - (thousands * 1000);

            var hundreds = remainder / 100;
            if (0 != hundreds)
            {
                buffer.Append(ToString(hundreds));
                buffer.Append(" hundred ");
            }

            remainder = remainder - (hundreds * 100);

            var skip = false;
            if (19 < remainder)
            {
                for (var i = 9; i > 1; i--)
                {
                    var tens = i * 10;
                    if (tens > remainder)
                    {
                        continue;
                    }

                    buffer.Append(_tens[i]);
                    if (tens != remainder)
                    {
                        buffer.Append('-');
                    }
                    else
                    {
                        skip = true;
                    }

                    remainder = remainder - tens;
                    break;
                }
            }

            buffer.Append(skip ? string.Empty : ToString(remainder));

            return buffer.ToString();
        }

        private string ToString(int value)
        {
            return _ones[value];
        }
    }
}